"""
AI算法配置
"""
from typing import Dict, List, Any
from pydantic import BaseSettings


class AIConfig(BaseSettings):
    """AI算法配置"""
    
    # 人员检测配置
    PERSON_DETECTION_ENABLED: bool = True
    PERSON_DETECTION_CONFIDENCE_THRESHOLD: float = 0.5
    PERSON_DETECTION_NMS_THRESHOLD: float = 0.4
    PERSON_DETECTION_MAX_DETECTIONS: int = 100
    PERSON_DETECTION_INPUT_SIZE: tuple = (640, 640)
    PERSON_DETECTION_ENABLE_TRACKING: bool = True
    PERSON_DETECTION_TRACKING_MAX_AGE: int = 30
    
    # 行为分析配置
    BEHAVIOR_ANALYSIS_ENABLED: bool = True
    BEHAVIOR_ANALYSIS_INTERVAL: float = 1.0  # 秒
    BEHAVIOR_ANALYSIS_MAX_TRACK_AGE: int = 300  # 秒
    BEHAVIOR_ANALYSIS_SPEED_THRESHOLD_RUNNING: float = 50.0  # 像素/秒
    BEHAVIOR_ANALYSIS_LOITERING_TIME_THRESHOLD: float = 30.0  # 秒
    BEHAVIOR_ANALYSIS_INTERACTION_DISTANCE_THRESHOLD: float = 100.0  # 像素
    
    # 人群密度分析配置
    CROWD_DENSITY_ENABLED: bool = True
    CROWD_DENSITY_ANALYSIS_INTERVAL: float = 60.0  # 秒
    CROWD_DENSITY_GRID_SIZE: int = 20
    CROWD_DENSITY_WARNING_THRESHOLD: float = 0.7
    CROWD_DENSITY_CRITICAL_THRESHOLD: float = 0.9
    
    # 智能告警配置
    INTELLIGENT_ALERT_ENABLED: bool = True
    INTELLIGENT_ALERT_CONFIDENCE_THRESHOLD: float = 0.6
    INTELLIGENT_ALERT_FREQUENCY_THRESHOLD: int = 5
    INTELLIGENT_ALERT_TIME_WINDOW: int = 300  # 秒
    INTELLIGENT_ALERT_COOLDOWN_PERIOD: int = 300  # 秒
    
    # 疏散系统配置
    EVACUATION_ENABLED: bool = True
    EVACUATION_MONITORING_INTERVAL: float = 10.0  # 秒
    EVACUATION_PATHFINDING_GRID_SIZE: int = 10
    EVACUATION_WALKING_SPEED: float = 1.2  # 米/秒
    EVACUATION_EMERGENCY_WALKING_SPEED: float = 2.0  # 米/秒
    
    # 模型配置
    MODEL_CACHE_DIR: str = "./models"
    MODEL_DOWNLOAD_TIMEOUT: int = 300  # 秒
    MODEL_INFERENCE_TIMEOUT: int = 30  # 秒
    
    # GPU配置
    GPU_ENABLED: bool = True
    GPU_DEVICE_ID: int = 0
    GPU_MEMORY_FRACTION: float = 0.8
    GPU_ALLOW_GROWTH: bool = True
    
    # 性能监控配置
    PERFORMANCE_MONITORING_ENABLED: bool = True
    PERFORMANCE_METRICS_RETENTION: int = 1000  # 保留最近N条记录
    PERFORMANCE_BENCHMARK_ENABLED: bool = False
    
    # 数据存储配置
    AI_DATA_RETENTION_DAYS: int = 30
    AI_RESULTS_BATCH_SIZE: int = 100
    AI_RESULTS_FLUSH_INTERVAL: int = 60  # 秒
    
    # 通知配置
    NOTIFICATION_EMAIL_ENABLED: bool = False
    NOTIFICATION_SMS_ENABLED: bool = False
    NOTIFICATION_WEBHOOK_ENABLED: bool = True
    NOTIFICATION_WEBHOOK_URL: str = ""
    NOTIFICATION_WEBHOOK_TIMEOUT: int = 10  # 秒
    
    # 调试配置
    AI_DEBUG_MODE: bool = False
    AI_LOG_LEVEL: str = "INFO"
    AI_SAVE_DEBUG_IMAGES: bool = False
    AI_DEBUG_IMAGE_DIR: str = "./debug_images"
    
    class Config:
        env_prefix = "AI_"
        case_sensitive = True


# 默认AI模型配置
DEFAULT_AI_MODELS = {
    "person_detection": {
        "yolov8n_person": {
            "model_name": "YOLOv8 Nano Person Detection",
            "model_path": "yolov8n.pt",
            "algorithm_type": "yolo",
            "input_size": (640, 640),
            "confidence_threshold": 0.5,
            "nms_threshold": 0.4,
            "max_detections": 100,
            "gpu_enabled": True,
            "batch_size": 1
        },
        "yolov8s_person": {
            "model_name": "YOLOv8 Small Person Detection", 
            "model_path": "yolov8s.pt",
            "algorithm_type": "yolo",
            "input_size": (640, 640),
            "confidence_threshold": 0.5,
            "nms_threshold": 0.4,
            "max_detections": 100,
            "gpu_enabled": True,
            "batch_size": 1
        }
    },
    "pose_estimation": {
        "mediapipe_pose": {
            "model_name": "MediaPipe Pose Estimation",
            "model_path": "mediapipe_pose",
            "algorithm_type": "mediapipe",
            "input_size": (640, 480),
            "confidence_threshold": 0.5,
            "gpu_enabled": False,
            "batch_size": 1
        }
    }
}

# 默认告警规则配置
DEFAULT_ALERT_RULES = [
    {
        "rule_id": "person_count_high",
        "rule_name": "人员数量过多告警",
        "conditions": [
            {
                "field": "total_count",
                "operator": ">",
                "value": 15,
                "duration": 30
            }
        ],
        "alert_level": "high",
        "cooldown_period": 300,
        "enabled": True
    },
    {
        "rule_id": "crowding_detected",
        "rule_name": "人群聚集告警",
        "conditions": [
            {
                "field": "behavior_type",
                "operator": "==",
                "value": "crowding"
            },
            {
                "field": "confidence",
                "operator": ">=",
                "value": 0.7
            }
        ],
        "alert_level": "medium",
        "cooldown_period": 180,
        "enabled": True
    },
    {
        "rule_id": "abnormal_behavior",
        "rule_name": "异常行为告警",
        "conditions": [
            {
                "field": "behavior_type",
                "operator": "in",
                "value": ["fighting", "running"]
            },
            {
                "field": "confidence",
                "operator": ">=",
                "value": 0.6
            }
        ],
        "alert_level": "critical",
        "cooldown_period": 60,
        "enabled": True
    },
    {
        "rule_id": "loitering_detected",
        "rule_name": "徘徊行为告警",
        "conditions": [
            {
                "field": "behavior_type",
                "operator": "==",
                "value": "loitering"
            },
            {
                "field": "duration",
                "operator": ">=",
                "value": 120
            },
            {
                "field": "confidence",
                "operator": ">=",
                "value": 0.5
            }
        ],
        "alert_level": "low",
        "cooldown_period": 600,
        "enabled": True
    }
]

# 默认疏散计划配置
DEFAULT_EVACUATION_PLANS = [
    {
        "plan_id": "crowd_evacuation",
        "plan_name": "人群聚集疏散计划",
        "trigger_conditions": {
            "density_level": {"operator": ">=", "value": "high"},
            "person_count": {"operator": ">", "value": 15}
        },
        "affected_zones": ["central", "entrance"],
        "estimated_duration": 10.0,
        "max_occupancy": 100,
        "emergency_level": "warning"
    },
    {
        "plan_id": "emergency_evacuation",
        "plan_name": "紧急疏散计划",
        "trigger_conditions": {
            "emergency_level": "critical",
            "anomaly_type": "overcrowding"
        },
        "affected_zones": ["central", "entrance", "exit"],
        "estimated_duration": 5.0,
        "max_occupancy": 200,
        "priority_groups": ["elderly", "disabled", "children"],
        "emergency_level": "critical"
    }
]

# 默认区域配置
DEFAULT_ZONES = [
    {
        "zone_id": "entrance",
        "zone_name": "入口区域",
        "coordinates": [(0, 0), (200, 0), (200, 150), (0, 150)],
        "max_capacity": 20,
        "warning_threshold": 0.6,
        "critical_threshold": 0.8
    },
    {
        "zone_id": "central",
        "zone_name": "中央区域",
        "coordinates": [(200, 150), (600, 150), (600, 450), (200, 450)],
        "max_capacity": 50,
        "warning_threshold": 0.7,
        "critical_threshold": 0.9
    },
    {
        "zone_id": "exit",
        "zone_name": "出口区域",
        "coordinates": [(600, 450), (800, 450), (800, 600), (600, 600)],
        "max_capacity": 15,
        "warning_threshold": 0.6,
        "critical_threshold": 0.8
    }
]

# 默认出口点配置
DEFAULT_EXIT_POINTS = [
    {
        "exit_id": "main_exit",
        "exit_name": "主出口",
        "coordinates": (400, 0),
        "capacity": 120,
        "is_emergency_exit": False,
        "accessibility_features": ["wheelchair_accessible", "wide_door"]
    },
    {
        "exit_id": "emergency_exit",
        "exit_name": "紧急出口",
        "coordinates": (800, 300),
        "capacity": 60,
        "is_emergency_exit": True,
        "accessibility_features": ["emergency_lighting"]
    },
    {
        "exit_id": "side_exit",
        "exit_name": "侧门出口",
        "coordinates": (0, 300),
        "capacity": 40,
        "is_emergency_exit": False,
        "accessibility_features": []
    }
]


def get_ai_config() -> AIConfig:
    """获取AI配置实例"""
    return AIConfig()


def get_model_config(model_type: str, model_id: str) -> Dict[str, Any]:
    """获取模型配置"""
    return DEFAULT_AI_MODELS.get(model_type, {}).get(model_id, {})


def get_alert_rules_config() -> List[Dict[str, Any]]:
    """获取告警规则配置"""
    return DEFAULT_ALERT_RULES.copy()


def get_evacuation_plans_config() -> List[Dict[str, Any]]:
    """获取疏散计划配置"""
    return DEFAULT_EVACUATION_PLANS.copy()


def get_zones_config() -> List[Dict[str, Any]]:
    """获取区域配置"""
    return DEFAULT_ZONES.copy()


def get_exit_points_config() -> List[Dict[str, Any]]:
    """获取出口点配置"""
    return DEFAULT_EXIT_POINTS.copy()